<?php

use Illuminate\Database\Capsule\Manager as DB;

#[店铺装修]
class DecorateController extends McommonController
{
    public function init()
    {
        $this->model = (new decorateModel)->withTrashed();
        $this->table = 'decorate';
        $this->primaryKey = 'id';
        parent::init();
    }

    #[模板列表]
    public function indexAction($returnData = FALSE)
    {
        if ($this->isPost()) {
            $type = $this->get('type', 'dianpu');
            if ($type) {
                array_push($this->condition, ['type', '=', $type]);
            }
            if (is_object($this->model)) {
                $query = $this->model;
            } else {
                $query = is_string($this->model) ? (new $this->model) : DB::table($this->table);
            }
            $query = $query->where('dianpu_id', $this->auth->dianpu_id);
            if (!empty($this->search)) {
                $query = $query->where(function ($query) {
                    foreach ($this->search as $v) {
                        if (isset($v[3]) && strtolower($v[3]) == 'or') {
                            $query = $query->orWhere([$v]);
                        } else {
                            $query = $query->where([$v]);
                        }
                    }
                });
            }
            if (!empty($this->condition)) {
                $query = $query->where($this->condition);
            }
            if (!empty($this->condition_in)) {
                foreach ($this->condition_in as $k => $v) {
                    $query = $query->whereIn($v[0], $v[1]);
                }
            }
            $total = $query->count();
            $sort = $this->get('sort', 'sortorder');
            $order = $this->get('order', 'desc');
            $query = $query->orderBy($sort, $order)->orderBy($this->primaryKey, 'DESC');
            $page = $this->get('page');

            if (!empty($page)) {
                $limit = $this->get('rows', 10);
                $offset = ($page - 1) * $limit;
                $query = $query->offset($offset)->limit($limit);
            }
            $rows = $query->get();
            if (!empty($this->appends)) {
                foreach ($this->appends as $append) {
                    $rows = $rows->append($append);
                }
            }
            if (!empty($this->hiddens)) {
                $rows = $rows->makeHidden($this->hiddens);
            }
            if ($rows->isEmpty()) {
                $dp = dianpuModel::query()->where('id', $this->auth->dianpu_id)->first();
                $newTpRows = [
                    'dianpu_id' => $this->auth->dianpu_id,
                    'name' => $dp->name . '的店铺模板',
                    'type' => 'dianpu',
                    'memo' => '店铺主页',
                    'status' => 'normal',
                    'platform' => 'H5,wxOfficialAccount,wxMiniProgram,App',
                    'weigh' => 500,
                    'created_at' => date('Y-m-d H:i:s')
                ];
                $newTpRowsId = decorateModel::query()->insertGetId($newTpRows);
                $total= 1;
                $rows = decorateModel::query()->where('id', $newTpRowsId)->get();
            }

            if ($returnData) {
                return ['total' => $total, 'rows' => $rows->toArray()];
            } else {
                json(['total' => $total, 'rows' => $rows]);
            }
        } else {
            $this->_view->display(strtolower($this->controller) . '/index.html');
        }
    }

    #[自定义页面]
    public function customAction()
    {
        $this->_view->display(strtolower($this->controller) . '/custom.html');
    }

    #[模板下架]
    public function downAction()
    {
        $id = $this->get('id');
        if ($this->isPost()) {
            $decorate = $this->model->find($id);
            if (!$decorate) {
                ret(30001, '未找到模板');
            }
            $decorate->status = 'hidden';
            $decorate->save();
            ret(0, '下架成功');
        }
    }

    #[模板发布]
    public function upAction()
    {
        $id = $this->get('id');
        if ($this->isPost()) {
            $decorate = $this->model->find($id);
            if (!$decorate) {
                ret(30001, '未找到模板');
            }
            decorateModel::where('status', 'normal')->where('type', $decorate->type)->update(['status' => 'hidden']);
            $decorate->status = 'normal';
            $decorate->save();
            ret(0, '发布成功');
        }
    }

    #[模板复制]
    public function copyAction()
    {
        $id = $this->get('id');
        if ($this->isPost()) {
            $newDecorate = $this->model->find($id)->makeHidden('id')->toArray();
            if (!$newDecorate) {
                ret(30001, '未找到模板');
            }
            $decorate_id = $this->model->insertGetId($newDecorate);
            $dcontent = decoratecontentModel::where('decorate_id', $id)->get()->makeHidden('id');
            foreach ($dcontent as $v) {
                $v->decorate_id = $decorate_id;
                decoratecontentModel::insert($v->toArray());
            }
            ret(0, '复制成功');
        }
    }

    #[添加模板]
    public function addAction()
    {
        if (!$this->isPost()) {
            $type = $this->get('type', 'shop');
            $dataset = $this->getTableColumn($this->table);
            $dataset['type'] = $type;
            $this->_view->assign('dataset', json_encode($dataset));
            $this->_view->display(strtolower($this->controller) . '/edit.html');
        } else {
            $input = $this->pageParam;
            $roles = [
                'name' => ['role' => 'required', 'msg' => '名称'],
            ];
            Validate::check($input, $roles);
            parent::addAction();
        }
    }

    #[编辑模板]
    public function editAction()
    {
        if (!$this->isPost()) {
            $input = $this->pageParam;
            $roles = [
                'id' => ['role' => "required|exists:{$this->table}.id", 'msg' => 'ID'],
            ];
            Validate::check($input, $roles);
            $dataset = $this->model->find($input['id']);
            $this->_view->assign('dataset', json_encode($dataset));
            $this->_view->display(strtolower($this->controller) . '/edit.html');
        } else {
            $input = $this->pageParam;
            $roles = [
                'id' => ['role' => "required|exists:{$this->table}.id", 'msg' => 'ID'],
                'name' => ['role' => 'required', 'msg' => '名称'],
            ];
            Validate::check($input, $roles);
            parent::editAction();
        }
    }

    #[页面装修]
    public function dodecorateAction()
    {
        $id = $this->get('id');
        $content = new decoratecontentModel();
        $query = $content->where('decorate_id', $id);
        if ($this->isPost()) {
            $params = $this->get("templateData");
            if ($params) {
                $params = json_decode($params, true);
                $result = false;
                Db::startTrans();
                try {
                    $decorateArray = [];
                    foreach ($params as $p => $a) {
                        foreach ($a as $c => &$o) {
                            if (isset($o['id'])) {
                                unset($o['id']);
                            }
                            $decorateArray[] = [
                                'category' => $p,
                                'content' => json_encode($o['content'], JSON_UNESCAPED_UNICODE),
                                'decorate_id' => $id,
                                'name' => $o['name'],
                                'type' => $o['type']
                            ];
                        }
                    }
                    $query->delete();
                    $result = new \app\admin\model\shopro\DecorateContent;
                    $result->saveAll($decorateArray);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error('请完善装修页面');
        }
        $template = $query->get()->toArray();
        if ($template) {
            foreach ($template as &$t) {
                $t['content'] = json_decode($t['content'], true);
            }
        } else {
            $template = [];
        }
        $categoryArray = array_column($template, 'category');
        $templateData = [];
        foreach ($categoryArray as $categoryKey => $category) {
            $templateData[$category][] = $template[$categoryKey];
        }
        $this->_view->assign('id', $id);
        $this->_view->assign('templateData', json_encode($templateData));
        $this->_view->display('decorate/dodecorate.html');
    }

    #[页面装修_保存]
    public function saveAction()
    {
        $id = $this->get('id');
        if ($this->isPost()) {
            $decorate = $this->model->find($id);

            if (!$decorate) {
                ret(30001, '未找到模板');
            }

            $params = $this->get("templateData");
            $result = $this->updateDecorateContent($id, $params);
            if ($result) {
                ret(0, '保存成功', $decorate);
            } else {
                ret(30002, '保存失败');
            }
        }
    }

    #[页面删除]
    public function deleteAction()
    {
        $id = $this->get('id');
        $decorate = $this->model->find($id);
        if (!$decorate) {
            ret(30001, '未找到模板');
        }
        $decorate->status = 'hidden';
        $decorate->save();
        parent::deleteAction();
    }

    private function updateDecorateContent($id, $params)
    {
        $result = false;

        if ($params) {
            $params = json_decode($params, true);
            DB::beginTransaction();
            try {
                $decorateArray = [];
                foreach ($params as $p => $a) {
                    foreach ($a as &$o) {
                        if (isset($o['id'])) {
                            unset($o['id']);
                        }
                        $decorateArray[] = [
                            'category' => $p,
                            'content' => json_encode($o['content'], JSON_UNESCAPED_UNICODE),
                            'decorate_id' => $id,
                            'name' => $o['name'],
                            'type' => $o['type']
                        ];
                    }
                }

                decoratecontentModel::where(['decorate_id' => $id])->delete();
                $result = new decoratecontentModel();
                $result->insert($decorateArray);
                DB::commit();
                return $result;
            } catch (Exception $e) {
                DB::rollback();
                ret(30003, $e->getMessage());
            }
        }
        return $result;
    }

    //店铺装修 保存首页截图
    public function saveDecorateImage($id)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('未找到模板'));
        }

        $image = $this->request->post('image');

        if ($image) {
            $row->image = $image;
            $row->save();
        }

        $this->success("更新成功");
    }

    /**
     * 页面装修 预览
     */
    public function preview($id)
    {
        //装修数据
        $decorate = $this->model->get($id);
        if (!$decorate) {
            $this->error('未找到该装修页面');
        }
        //临时预览数据
        $row = [
            'name' => "临时预览 {$decorate->name}",
            'type' => 'preview',
            'memo' => date("Y年m月d日 H:i:s", time()) . ' 创建',
            'status' => 'normal',
            'platform' => $decorate->platform
        ];
        $preview = $this->model->where('type', 'preview')->find();
        if ($preview) {
            DecorateContent::where('decorate_id', $preview->id)->delete();
            $preview->delete(true);
        }
        $this->model->save($row);
        $id = $this->model->id;
        $decorate = $this->model->getData();
        $params = $this->request->post("templateData");
        $this->updateDecorateContent($id, $params);
        $this->success($row['name'], null, $decorate);
    }

    #[选择商品]
    public function selectgoodsAction()
    {
        if ($this->isPost()) {
            $query = (new \app\modules\Merchant\models\goodsModel)->where('dianpu_id', $this->auth->dianpu_id);
            $category_ids = $this->get('category_ids');
            if ($category_ids) {
                $query = $query->whereRaw('FIND_IN_SET(?, category_ids)', [$category_ids]);
            }
            $keywords = $this->get('keywords');
            if (!empty($keywords)) {
                $query = $query->where('title', 'like', "%{$keywords}%")
                    ->orWhere('id', '=', $keywords);
            }
            $status = $this->get('status', 'up');
            if (!empty($status)) {
                $query = $query->where('status', $status);
            }
            $total = $query->count();
            $sort = $this->get('sort', 'sortorder');
            $order = $this->get('order', 'desc');
            $query = $query->orderBy($sort, $order)->orderBy($this->primaryKey, 'DESC');
            $page = $this->get('page');
            if (!empty($page)) {
                $limit = $this->get('rows', 10);
                $offset = ($page - 1) * $limit;
                $query = $query->offset($offset)->limit($limit);
            }
            $rows = $query->select('id', 'image', 'price', 'title', 'status')->get();
            $goodsStock = goodsskupriceModel::select(DB::raw('sum(stock) as allstock'), 'goods_id')->groupBy('goods_id')->pluck('allstock', 'goods_id');
            foreach ($rows as $row) {
                $row->stock = $goodsStock[$row->id];
            }
            json(['total' => $total, 'rows' => $rows]);
        } else {
            $ids = $this->get('ids');
            $selectedGoods = explode(',', $ids);
            $this->_view->assign('selectedGoods', goodsModel::whereIn('id', $selectedGoods)->select('id', 'image', 'price', 'title')->get()->toJson());
            $this->_view->assign('multiple', $this->get('multiple', 1));
            $this->_view->display(strtolower($this->controller) . '/selectgoods.html');
        }
    }

    #[选择商品分类]
    public function selectcategoryAction()
    {
        if ($this->isPost()) {
            $page = $this->get('page', 1);
            $limit = $this->get('rows', 10);
            $offset = ($page - 1) * $limit;
            $sort = $this->get('sort', 'weigh');
            $order = $this->get('order', 'desc');
            $query = \app\modules\Merchant\models\categoryModel::where('pid', '=', 0)->where('dianpu_id', $this->auth->dianpu_id);
            $keywords = trim($this->get('keywords', ''));
            if ($keywords !== '') {
                $query = $query->where('name', 'like', "%{$keywords}%");
            }
            $total = $query->count();
            $rows = $query->orderBy($sort, $order)
                ->orderBy('id', 'ASC')
                ->offset($offset)
                ->limit($limit)
                ->get();
            if ($rows->isNotEmpty()) {
                foreach ($rows as $item) {
                    $this->getChild($item);
                }
            }
            json(['total' => $total, 'rows' => $rows]);
        } else {
            if ($this->get('multiple') == 1) {
                $this->_view->display(strtolower($this->controller) . '/selectcategories.html');
            } else {
                $this->_view->display(strtolower($this->controller) . '/selectcategory.html');
            }
        }
    }

    #[选择富文本]
    public function selectRichtextAction()
    {
        if ($this->isPost()) {
            $page = $this->get('page', 1);
            $limit = $this->get('rows', 10);
            $offset = ($page - 1) * $limit;
            $sort = $this->get('sort', 'weigh');
            $order = $this->get('order', 'desc');
            $query = pagesModel::where('status', '=', 1);
            $keywords = trim($this->get('keywords', ''));
            if ($keywords !== '') {
                $query = $query->where('title', 'like', "%{$keywords}%");
            }
            $total = $query->count();
            $rows = $query->orderBy($sort, $order)
                ->orderBy('id', 'ASC')
                ->offset($offset)
                ->limit($limit)
                ->get();
            json(['total' => $total, 'rows' => $rows]);
        } else {
            $this->_view->display(strtolower($this->controller) . '/selectrichtext.html');
        }
    }

    #[选择自定义页面]
    public function selectCustomAction()
    {
        if ($this->isPost()) {
            $page = $this->get('page', 1);
            $limit = $this->get('rows', 10);
            $offset = ($page - 1) * $limit;
            $sort = $this->get('sort', 'weigh');
            $order = $this->get('order', 'desc');
            $query = decorateModel::where('type', '=', 'custom');
            $keywords = trim($this->get('keywords', ''));
            if ($keywords !== '') {
                $query = $query->where('name', 'like', "%{$keywords}%");
            }
            $total = $query->count();
            $rows = $query->orderBy($sort, $order)
                ->orderBy('id', 'ASC')
                ->offset($offset)
                ->limit($limit)
                ->get();
            json(['total' => $total, 'rows' => $rows]);
        } else {
            $this->_view->display(strtolower($this->controller) . '/selectcustom.html');
        }
    }

    #[选择秒杀]
    public function selectSeckillAction()
    {
        if ($this->isPost()) {
            $page = $this->get('page', 1);
            $limit = $this->get('rows', 10);
            $offset = ($page - 1) * $limit;
            $sort = $this->get('sort', 'weigh');
            $order = $this->get('order', 'desc');
            $query = new \app\modules\Admin\models\activityModel;
            $keywords = trim($this->get('keywords', ''));
            if ($keywords !== '') {
                $query = $query->where('name', 'like', "%{$keywords}%");
            }
            $total = $query->count();
            $rows = $query->orderBy($sort, $order)
                ->orderBy('id', 'ASC')
                ->offset($offset)
                ->limit($limit)
                ->get();
            json(['total' => $total, 'rows' => $rows]);
        } else {
            $this->_view->display(strtolower($this->controller) . '/selectseckill.html');
        }
    }

    #[选择链接]
    public function selectlinkAction()
    {
        if ($this->isPost()) {
            $list = \app\modules\Merchant\models\linkModel::groupBy('group')->with('children')->select('group')->where('group', '商品')->get()->toArray();
            ret(0, '链接列表', $list);
        } else {
            $this->_view->assign('index', $this->get('index', 0));
            $this->_view->display(strtolower($this->controller) . '/selectlink.html');
        }
    }

    private function getChild(&$item)
    {
        $children = categoryModel::where('pid', $item->id)->orderBy('weigh', 'DESC')->orderBy('id', 'ASC')->get();
        if ($children->isNotEmpty()) {
            $item->children = $children;
            foreach ($children as $v) {
                $v->name = htmlentities($v->name);
                $this->getChild($v);
            }
        }
    }

}
